package com.uchiha.nova.mainService.config;

import com.uchiha.nova.core.model.entity.OauthClientDetails;
import com.uchiha.nova.core.tool.constant.RedisCacheConstants;
import com.uchiha.nova.mainService.mapper.OauthClientDetailsMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 周林静
 * @Date 2025-03-25 8:53
 * @Version 1.0
 */
@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner, Ordered {
    @Resource
    OauthClientDetailsMapper oauthClientDetailsMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public int getOrder(){
        return 1;
    }

    @Value("${nova.oauth.token-key}")
    String tokenKey;

    public static Map<String, String> clients = new HashMap<>();
    @Override
    public void run(ApplicationArguments var1){
        List<OauthClientDetails> list = oauthClientDetailsMapper.selectList(null);

        list.forEach(item->{
            clients.put(item.getClientId(),item.getClientSecret());
            redisTemplate.opsForValue().set(RedisCacheConstants.NOVA_OAUTH_CLIENT+item.getClientId(),item);
        });
        redisTemplate.opsForValue().set(RedisCacheConstants.CLIENT_DETAIL,clients);
        redisTemplate.opsForValue().set(RedisCacheConstants.NOVA_OAUTH_TOKENKEY,tokenKey);
        redisTemplate.convertAndSend(RedisCacheConstants.ROLE_SERVICE,"client");
        log.info("oauthClientDetail-init!");
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    public static Map<String, String> getClients() {
        return clients;
    }
}
